package com.neusoft.neuiotms.dcom.converter.malfunction;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcom.dto.malfunction.MalfunctionCustomerReviewDTO;
import com.neusoft.neuiotms.dcom.model.malfunction.MalfunctionCustomerReview;
import com.neusoft.neuiotms.dcom.model.malfunction.MalfunctionCustomerReviewAnnex;
import com.neusoft.neuiotms.dcom.repository.malfunction.MalfunctionCustomerReviewAnnexRepository;
import com.neusoft.neuiotms.dcom.repository.malfunction.MalfunctionCustomerReviewRepository;

@Component
public class MalfunctionCustomerReviewConverter
        extends AbstractConverter<MalfunctionCustomerReview, MalfunctionCustomerReviewDTO> {

    @Autowired
    private MalfunctionCustomerReviewRepository customerReviewRepository;
    @Autowired
    private MalfunctionCustomerReviewAnnexRepository customerReviewAnnexRepository;
    @Autowired
    private MalfunctionCustomerReviewAnnexConverter customerReviewAnnexConverter;

    @Override
    public MalfunctionCustomerReview toModel(final MalfunctionCustomerReviewDTO dto) {

        MalfunctionCustomerReview model;
        if (dto.isNew()) {
            model = new MalfunctionCustomerReview();
        } else {
            model = this.customerReviewRepository.getOne(dto.getId());
        }

        model.setTaskId(dto.getTaskId());
        model.setWorkNum(dto.getWorkNum());
        model.setSatisfaction(dto.getSatisfaction());

        final List<MalfunctionCustomerReviewAnnex> annexs = model.getAnnex().stream().collect(Collectors.toList());

        annexs.forEach(k -> {
            model.getAnnex().remove(k);
            this.customerReviewAnnexRepository.delete(k);
        });

        dto.getAnnex().stream().map(s -> {
            final MalfunctionCustomerReviewAnnex annex = this.customerReviewAnnexConverter.toModel(s);
            annex.setCustomerReview(model);
            return annex;
        }).forEach(model.getAnnex()::add);

        return model;
    }

    @Override
    public MalfunctionCustomerReviewDTO toDTO(final MalfunctionCustomerReview model, final boolean forListView) {

        final MalfunctionCustomerReviewDTO dto = new MalfunctionCustomerReviewDTO();
        dto.setId(model.getId());
        dto.setTaskId(model.getTaskId());
        dto.setWorkNum(model.getWorkNum());
        dto.setSatisfaction(model.getSatisfaction());

        model.getAnnex().stream().map(s -> this.customerReviewAnnexConverter.toDTO(s)).filter(k -> null != k)
                .forEach(dto.getAnnex()::add);
        return dto;
    }

}
